<template>
  <div>
    <Page auto-content-height>
      <FosoCard :showheader="false" class="!px-0 !pt-0">
        <FosoForm
          ref="formRef"
          :form-columns="formColumns"
          :form-columns-num="8"
          :form-data="formData"
          :form-expand="true"
          label-width="auto"
          @search-handle="searchHandle"
        />
      </FosoCard>
      <FosoTable
        ref="FosoTable"
        :columns="columns"
        :request-api="getDicListData"
        :toolbarbutton-name="$t('sys.dictionary.addDictionary')"
        class="!h-[90%]"
        @add="openDrawerHandle('add', $event)"
        @delete="DeleteHandle($event)"
        @edit="openDrawerHandle('edit', $event)"
      />
    </Page>
    <!-- 弹窗框 -->
    <Drawer class="w-[40%]" @refresh="reloadTable" />
  </div>
</template>

<script setup lang="tsx">
import { Page, useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { ElSwitch } from 'element-plus';

import {
  deleteDictionary,
  getDictionaryList,
  updateDictionary,
} from '#/api/sys/dictionary';

import ExtraDrawer from './components/drawer.vue';

const FosoTableRef = useTemplateRef('FosoTable');
// 弹窗连接
const [Drawer, drawerApi] = useVbenDrawer({
  // 连接抽离的组件
  connectedComponent: ExtraDrawer,
});
// 表单实例
const formRef = ref();
// 表单数据
const formData = ref({
  name: '',
});
// 表单配置项
const formColumns = ref([
  {
    label: $t('sys.dictionary.name'),
    prop: 'name',
    span: 8,
    xType: 'Input',
    componentProps: {
      placeholder: $t('common.form.pleaseInput'),
      clearable: true,
    },
  },
]);

// 表格获取数据
const getDicListData = async (params: any) => {
  const { page = 1, pageSize = 5 } = params;
  const res: any = await getDictionaryList({
    page,
    pageSize,
    ...formData.value,
  });
  return {
    total: res.total,
    items: res.data,
  };
};

const columns = computed(() => [
  { type: 'checkbox', width: 80 },
  { field: 'name', title: $t('sys.dictionary.displayName') },
  { field: 'title', title: $t('sys.dictionary.name') },
  {
    field: 'status',
    title: $t('sys.department.status'),
    slots: {
      default: ({ row }: any) => {
        return (
          <ElSwitch
            active-text="是"
            inactive-text="否"
            inline-prompt
            modelValue={Boolean(row.status)}
            onUpdate:modelValue={() => changeStatus(row)}
          />
        );
      },
    },
  },
  { field: 'createTime', title: $t('sys.menu.createTime'), width: 180 },
  {
    field: 'action',
    title: $t('sys.menu.operation'),
    slots: { default: 'action' },
  },
]);

/**
 * @author Buke
 * @description 切换状态
 * @param {any} row - 要切换状态的行数据。
 * @returns {void}
 */
async function changeStatus(row: any): Promise<void> {
  try {
    await updateDictionary({
      id: row.id,
      status: Number(!row.status),
    });
    row.status = !row.status; // 切换状态
    ElMessage.success('操作成功');
  } catch {
    ElMessage.error('操作失败');
  }
}

/**
 * @author Buke
 * @description 删除字典
 * @param {any} row - 要删除的行数据。
 * @returns {void}
 */
async function DeleteHandle(row: any): Promise<void> {
  try {
    await deleteDictionary({
      ids: [row.id],
    });
    ElMessage.success('删除成功');
    FosoTableRef.value?.gridApi.reload();
  } catch {
    ElMessage.error('删除失败');
  }
}

/**
 * @author Buke
 * @description 打开弹窗
 * @param {string} type - 操作类型，'edit' 表示编辑，'add' 表示新增。
 * @param {any} row - 要编辑的行数据对象，包含字典相关信息。
 * @returns {void}
 */
const openDrawerHandle = (type: string, row?: any): void => {
  if (type === 'edit') {
    drawerApi.setState({ title: $t('sys.dictionary.editDictionary') });
    drawerApi.setData({ type: 'editData', id: row.id });
    drawerApi.open(); // 注意弹框打开需要分开，不能用同一个
  }
  if (type === 'add') {
    drawerApi.setState({ title: $t('sys.dictionary.addDictionary') });
    drawerApi.setData({ type: 'addData' });
    drawerApi.open(); // 注意弹框打开需要分开，不能用同一个
  }
};

/**
 * @author Buke
 * @description 搜索字典
 * @returns {void}
 */
const searchHandle = (): void => {
  FosoTableRef.value?.gridApi.query();
};

/**
 * @author Buke
 * @description 处理表格数据加载完成后的操作，如更新表格数据。
 * @returns {void}
 */
const reloadTable = (): void => {
  FosoTableRef.value?.gridApi.reload();
  drawerApi.close();
};
</script>
